package com.hmall.item.search.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.PageDTO;

import com.hmall.common.pojo.Item;
import com.hmall.common.pojo.ItemDoc;
import com.hmall.item.search.pojo.RequestParams;
import com.hmall.item.search.service.SearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 29143
 */
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ItemClient itemClient;


    /**
     * 搜索商品信息
     *
     * @param params
     * @return
     */
    @Override
    public PageDTO<ItemDoc> getList(RequestParams params) {
        //创建请求对象
        SearchRequest request = new SearchRequest("item");
        SearchSourceBuilder source = request.source();
        buildBasicQuery(params, source);
        //构建分页参数
        Integer page = params.getPage();//页码
        Integer size = params.getSize();//每页条数
        source.from((page - 1) * size);
        source.size(size);

        return itemResult(request);
    }


    /**
     * 自动补全
     *
     * @param key
     * @return
     */
    @Override
    public List<String> getSuggestion(String key) {

        //创建请求对象
        SearchRequest request = new SearchRequest("item");
        SearchSourceBuilder source = request.source();
        //准备DSL
        source.suggest(new SuggestBuilder().addSuggestion("mySuggestion", SuggestBuilders.completionSuggestion("suggestion").prefix(key).skipDuplicates(true).size(10)));
        try {
            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析结果
            Suggest suggest = response.getSuggest();
            //根据不全查询名称,获取补全结果
            CompletionSuggestion mySuggestion = suggest.getSuggestion("mySuggestion");
            //获取options
            List<CompletionSuggestion.Entry.Option> options = mySuggestion.getOptions();
            List<String> list = new ArrayList<>();
            //遍历
            for (CompletionSuggestion.Entry.Option option : options) {
                String s = option.getText().toString();
                list.add(s);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    /**
     * 过滤项聚合工程
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {

        try {
            //创建请求对象
            SearchRequest request = new SearchRequest("item");
            SearchSourceBuilder source = request.source();
            buildBasicQuery(params, source);
            //调用聚合方法
            buildAggregation(source);
            //发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            //获取根据品牌名称,获取品牌结果,并封装到map集合当中
            List<String> brandAgg = getAggByName(aggregations, "brandAgg");
            result.put("brand", brandAgg);
            //获取根据分类名称,获取分类结果,并封装到map集合当中
            List<String> categoryAgg = getAggByName(aggregations, "categoryAgg");
            result.put("category", categoryAgg);
            return result;
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    /**
     * 定义一个聚合方法
     * 构建聚合条件
     *
     * @param source
     */
    private void buildAggregation(SearchSourceBuilder source) {

        //设置根据品牌分组
        source.aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(100));

        //设置根据分类分组
        source.aggregation(AggregationBuilders.terms("categoryAgg").field("category").size(100));

    }

    /**
     * 定义一个方法,获取分组之后组名
     *
     * @param aggregations
     * @param aggName
     * @return
     */
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        //根据聚合名称获取聚合结果
        Terms terms = aggregations.get(aggName);
        //获取buckets
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        //创建一个list集合,用来就收key
        List<String> brandList = new ArrayList<>();
        //遍历集合
        for (Terms.Bucket bucket : buckets) {
            //获取key,并封装到list集合当中
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        //返回list集合
        return brandList;
    }

    /**
     * 封装查询条件
     *
     * @param params
     * @param source
     */
    private void buildBasicQuery(RequestParams params, SearchSourceBuilder source) {

        //创建BoolQueryBuilder对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //构建关键词key match搜索 must 算分
        String key = params.getKey();
        System.out.println(key);
        //判断前端传过来的key是否为空
        if (StringUtils.isNotBlank(key)) {
            //当前端传过来的key不为空时,就根据所有字段查询包含key的数据
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
            //创建高亮显示对象
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            //构建高亮三要素
            highlightBuilder.field("name");
            highlightBuilder.preTags("<font color='red'>");
            highlightBuilder.postTags("</font>");
            //关闭字段匹配检查
            highlightBuilder.requireFieldMatch(false);
            source.highlighter(highlightBuilder);
        } else {
            //当前端传过来的key为空时,就查询所有数据
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }

        String sortBy = params.getSortBy();
        if (StringUtils.isNotBlank(sortBy)) {
            if ("sold".equals(sortBy)) {
                source.sort(sortBy, SortOrder.DESC);
            }
            if ("price".equals(sortBy)) {
                source.sort(sortBy, SortOrder.ASC);
            }
        }

        //构建分类搜索
        String category = params.getCategory();
        if (StringUtils.isNotBlank(category)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category", category));
        }

        //构建品牌 brand term搜索
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));
        }


        //构建价格范围 range搜索
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte((minPrice)*100).lte((maxPrice)*100));
        }
        source.query(boolQueryBuilder);
        //算分查询条件
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(boolQueryBuilder, //原来的条件
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAD", "true"),//代表打广告的酒店
                        ScoreFunctionBuilders.weightFactorFunction(10)//设置分数
                )}).scoreMode(FunctionScoreQuery.ScoreMode.MULTIPLY); //设置加权方式: 相乘

        source.query(functionScoreQuery);
    }

    /**
     * 抽取公共的代码,定义一个方法,解析获取的结果
     *
     * @param request
     * @return
     */
    private PageDTO<ItemDoc> itemResult(SearchRequest request) {
        try {
            //执行请求得到响应结果
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析响应结果
            SearchHits searchHits = response.getHits();
            //查询总数量
            long total = searchHits.getTotalHits().value;
            //创建一个list集合
            List<ItemDoc> list = new ArrayList<>();
            //按照kibana的格式,解析结果
            SearchHit[] hits = searchHits.getHits();
            for (SearchHit hit : hits) {
                //获取文档内容
                String docJson = hit.getSourceAsString();
                ItemDoc itemDoc = JSON.parseObject(docJson, ItemDoc.class);
                //单独获取高亮显示结果,定义一个map集合,用来获取高亮显示的结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields != null && highlightFields.size() > 0) {
                    HighlightField highlightField = highlightFields.get("name");
                    String s = highlightField.getFragments()[0].toString();
                    itemDoc.setName(s);
                }
                list.add(itemDoc);
            }
            return new PageDTO<ItemDoc>(total, list);
        } catch (Exception e) {
            throw new RuntimeException();
        }

    }


    /**
     * 根据id删除商品
     *
     * @param id
     */
    @Override
    public void deleteById(String id) {
        try {
            DeleteRequest request = new DeleteRequest("item", id);
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    /**
     * 添加商品
     *
     * @param id
     */
    @Override
    public void insertById(String id) {
        try {
            //根据id查询酒店数据
            Item item = itemClient.findById(Long.valueOf(id));
            //转换文档类型
            ItemDoc itemDoc = new ItemDoc(item);
            //创建请求对象
            IndexRequest request = new IndexRequest("item");
            request.id(String.valueOf(item.getId()));
            //准备JSON文档
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            //发送请求
            client.index(request,RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

}
